import axios from 'axios'
class TApi {
  constructor() {
    this.config = {
      localKey: 'appApiLocalKey',
    }
    this.pageState = {}
  }
  callApi(apiUrl, compCode, action, params, method = 'post') {
    var me = this
    var res = {}
    return new Promise((su, fa) => {
      try {
        var url = [apiUrl, compCode, action].join('/')
        console.log(url)
        if (method.toLowerCase() == 'post') {
          var ps = params && params != null ? params : {}
          axios
            .post(url, ps, {
              headers: {
                'Content-Type': 'application/json',
              },
            })
            .then((res) => {
              su(res.data)
            })
            .catch((error) => {
              console.log(error)
              su(res)
            })
        } else if (method.toLowerCase() == 'get') {
          var ps = params && params != null ? params : {}
          if (Object.keys(ps).length > 0) {
            if (url.indexOf('?') > 0) {
              url = url + '&'
            } else {
              url = url + '?'
            }
            var kvs = Object.keys(ps).map((k) => {
              return k + '=' + ps[k]
            })
            url = url + kvs.join('&')
          }
          axios.get(url).then((_res) => {
            su(_res.data)
          })
        } else {
          su()
        }
      } catch (error) {
        su(res)
      }
    })
  }
  getSessionObj(key, defaultObj) {
    var res = defaultObj
    try {
      var data = window.sessionStorage.getItem(key)
      if (data && data != null && data != '') {
        res = JSON.parse(data)
      }
    } catch (error) {
      console.log(error)
    }
    return res
  }
  setSessionObj(key, obj) {
    try {
      window.sessionStorage.setItem(key, JSON.stringify(obj))
    } catch (error) {
      console.log(error)
    }
  }
}

class TFeTsApi {
  constructor() {
    this.apiUrl = '/apiFets'
    this.apiPath = 'fetsComp'
    this.api = api
    this.actionCode = {
      duelReset: 'duelReset',
      duelStart: 'duelStart',
      duelStop: 'duelStop',
      setReset: 'setReset',
      setStart: 'setStart',
      setStop: 'setStop',
    }
  }
  // 获取字典
  getDicts() {
    var me = this
    var res = {}
    return new Promise((su, fa) => {
      try {
        api.callApi(me.apiUrl, me.apiPath, 'getDicts', {}).then((_res) => {
          if (_res && _res.status == 1) {
            res = _res.result
          }
          su(res)
        })
      } catch (error) {
        console.log(error)
        su(res)
      }
    })
  }
  getDuelList(scheduleStatus, phaseCode) {
    var me = this
    var res = {
      status: 0,
    }
    return new Promise((su, fa) => {
      try {
        api
          .callApi(me.apiUrl, me.apiPath, 'getDuelList', { scheduleStatus, phaseCode })
          .then((_res) => {
            if (_res && _res.status == 1) {
              res = _res.result
            }
            su(res)
          })
      } catch (error) {
        console.log(error)
        su(res)
      }
    })
  }

  getDuelInfoPro(duelId) {
    var me = this
    var duelInfo = {
      duel: {},
      memA: {},
      memB: {},
      left: {},
      right: {},
      sets: [],
      currentSet: {},
    }
    return new Promise((su, fa) => {
      try {
        var t0 = new Date().getTime()
        api.callApi(me.apiUrl, me.apiPath, 'getDuelInfo', { duelId }).then((res) => {
          try {
            console.log(res)
            var duelKeys = [
              'dId',
              'duelId',
              'gameCodeCode',
              'eventId',
              'eventCode',
              'eventName',
              'teamFlag',
              'phaseId',
              'phaseCode',
              'phaseName',
              'duelType',
              'setNums',
              'setOrder',
              'duelCode',
              'scheduleTime',
              'localtion',
              'scheduleStatus',
              'startTime',
              'endTime',
              'nextDuelId',
              'preDuelId',
              'changeFlag',
              'subSetFlag',
            ]
            var duelMemAKeys = [
              'compAId',
              'compAName',
              'delegationAName',
              'chgAthAId',
              'chgAthAName',
              'scoreA',
              'redCardA',
              'yellowCardA',
              'priorityA',
              'IRMA',
            ]
            var duelMemBKeys = [
              'compBId',
              'compBName',
              'delegationBName',
              'chgAthBId',
              'chgAthBName',
              'scoreB',
              'redCardB',
              'yellowCardB',
              'priorityB',
              'IRMB',
            ]
            var setKeys = [
              'sId',
              'setKey',
              'setId',
              'duelId',
              'setOrder',
              'subSetFlag',
              'scheduleStatus',
              'startTime',
              'endTime',
            ]
            var setMemAKeys = [
              'athAId',
              'athAChgId',
              'athAName',
              'athAChgName',
              'scoreA',
              'redCardA',
              'yellowCardA',
              'priorityA',
              'IRMA',
              'chgAFlag',
              'athAInName',
              'setScoreA',
              'setRedCardA',
              'setYellowCardA',
            ]
            var setMemBKeys = [
              'athBId',
              'athBChgId',
              'athBName',
              'athBChgName',
              'scoreB',
              'redCardB',
              'yellowCardB',
              'priorityB',
              'IRMB',
              'chgBFlag',
              'athBInName',
              'setScoreB',
              'setRedCardB',
              'setYellowCardB',
            ]
            duelKeys.forEach((k) => {
              duelInfo.duel[k] = res.result.result[k]
            })
            duelMemAKeys.forEach((k) => {
              duelInfo.memA[k] = res.result.result[k]
            })
            duelMemBKeys.forEach((k) => {
              duelInfo.memB[k] = res.result.result[k]
            })
            res.result.result.sets.forEach((set) => {
              var setInfo = {
                memA: {},
                memB: {},
                left: {},
                right: {},
              }
              setKeys.forEach((sk) => {
                setInfo[sk] = set[sk]
              })
              setMemAKeys.forEach((sk) => {
                setInfo.memA[sk] = set[sk]
              })
              setMemBKeys.forEach((sk) => {
                setInfo.memB[sk] = set[sk]
              })
              setInfo.left = setInfo.memA
              setInfo.right = setInfo.memB
              duelInfo.sets.push(setInfo)
            })
            duelInfo.left = duelInfo.memA
            duelInfo.right = duelInfo.memB
            duelInfo.currentSet = duelInfo.sets.find((s) => {
              return (s.setOrder = duelInfo.duel.setOrder)
            })
            var t1 = new Date().getTime()
            console.log('time:', t1 - t0, JSON.stringify(duelInfo).length)
          } catch (er) {
            console.log(er)
          }
          console.log('duelinfo', duelInfo)
          su(duelInfo)
        })
      } catch (error) {
        console.log(error)
        su(duelInfo)
      }
    })
  }
  getDuelInfo(duelId) {
    var me = this
    var res = {
      status: 0,
    }
    return new Promise((su, fa) => {
      try {
        api.callApi(me.apiUrl, me.apiPath, 'getDuelInfo', { duelId }).then((_res) => {
          if (_res && _res.status == 1) {
            res = _res.result
            // var currentSet = res.result.sets.find((item) => item.setOrder == res.result.setOrder)
            // Object.keys(currentSet).forEach((item) => {
            //   res['curSet_' + item] = currentSet[item]
            // })
          }
          su(res)
        })
      } catch (error) {
        console.log(error)
        su(res)
      }
    })
  }
  // 获取第几局的数据
  getSetInfo(setKey) {
    var me = this
    var res = {
      status: 0,
    }
    return new Promise((su, fa) => {
      try {
        api.callApi(me.apiUrl, me.apiPath, 'getSetInfo', { setKey }).then((_res) => {
          if (_res && _res.status == 1) {
            res = _res.result
          }
          su(res)
        })
      } catch (error) {
        console.log(error)
        su(res)
      }
    })
  }
  // 获取裁判器数据
  getReferee() {
    var me = this
    var res = {
      status: 0,
    }
    return new Promise((su, fa) => {
      try {
        api.callApi(me.apiUrl, me.apiPath, 'getReferee', {}).then((_res) => {
          if (_res && _res.status == 1) {
            res = _res.result
          }
          su(res)
        })
      } catch (error) {
        console.log(error)
        su(res)
      }
    })
  } /* 
          actionCode取：
          duelReset: 'duelReset',
          duelStart: 'duelStart',
          duelStop: 'duelStop',
          duelStop_reback: 'duelStop_reback',  撤回结束
      */
  // 开始、停止、复位
  //对阵操作
  action(actionCode, duelId = '', setKey = '') {
    var me = this
    var res = {
      status: 0,
    }
    return new Promise((su, fa) => {
      try {
        console.log('action', actionCode, duelId, setKey)
        var ps = {}
        var flag = 0
        if (
          actionCode == 'duelReset' ||
          actionCode == 'duelStart' ||
          actionCode == 'duelStop' ||
          actionCode == 'duelStop_reback'
        ) {
          ps.duelId = duelId
          flag = 1
        } else if (
          actionCode == 'setReset' ||
          actionCode == 'setStart' ||
          actionCode == 'setStop'
        ) {
          ps.setKey = setKey
          flag = 1
        } else {
          res.status = -1
          res.msg = 'actionCode error.'
        }
        if (flag) {
          api.callApi(me.apiUrl, me.apiPath, actionCode, ps).then((_res) => {
            if (_res && _res.status == 1) {
              res = _res.result
            }
            su(res)
          })
        } else {
          su(res)
        }
      } catch (error) {
        console.log(error)
        su(res)
      }
    })
  }
  // 设置当前是第几局
  setDuelSetOrder(duelId, setOrder) {
    var me = this
    var res = {
      status: 0,
    }
    return new Promise((su, fa) => {
      try {
        api.callApi(me.apiUrl, me.apiPath, 'setDuelSetOrder', { duelId, setOrder }).then((_res) => {
          if (_res && _res.status == 1) {
            res = _res.result
          }
          su(res)
        })
      } catch (error) {
        console.log(error)
        su(res)
      }
    })
  }

  // 新增一个附加局（在最后一局仍然比分的情况下）
  duelAddSubSet(duelId) {
    var me = this
    var res = {
      status: 0,
    }
    return new Promise((su, fa) => {
      try {
        api.callApi(me.apiUrl, me.apiPath, 'duelAddSubSet', { duelId }).then((_res) => {
          if (_res && _res.status == 1) {
            res = _res.result
          }
          su(res)
        })
      } catch (error) {
        console.log(error)
        su(res)
      }
    })
  }

  //设置对阵状态数据
  /*
    newStatus ={ 
        "setOrder" , duelStatus['setOrder'] ,
        "scoreA" , duelStatus['scoreA'] ,
        "redCardA" , duelStatus['redCardA'] ,
        "yellowCardA" , duelStatus['yellowCardA'] ,
        "priorityA" , duelStatus['priorityA'] ,
        "scoreB" , duelStatus['scoreB'] ,
        "redCardB" , duelStatus['redCardB'] ,
        "yellowCardB" , duelStatus['yellowCardB'] ,
        "priorityB" , duelStatus['priorityB'] 
    }
    可以只设置其中的一个或多个属性
  */
  duelSetStatus(duelId, newStatus) {
    var me = this
    var res = {
      status: 0,
    }
    return new Promise((su, fa) => {
      try {
        api.callApi(me.apiUrl, me.apiPath, 'duelSetStatus', { duelId, newStatus }).then((_res) => {
          if (_res && _res.status == 1) {
            res = _res.result
          }
          su(res)
        })
      } catch (error) {
        console.log(error)
        su(res)
      }
    })
  }

  // 打点
  setPoint(sender, duelId, setOrder, reasonCode, tag = {}) {
    var me = this
    var res = {
      status: 0,
    }
    return new Promise((su, fa) => {
      try {
        var ps = {
          sender,
          duelId,
          setOrder,
          reasonCode,
          tag,
        }
        api.callApi(me.apiUrl, me.apiPath, 'setPoint', ps).then((_res) => {
          if (_res && _res.status == 1) {
            res = _res.result
          }
          su(res)
        })
      } catch (error) {
        console.log(error)
        su(res)
      }
    })
  }

  //换人
  setChange(setKey, pos, athId = '', athName = '') {
    var me = this
    var res = {
      status: 0,
    }
    return new Promise((su, fa) => {
      try {
        var ps = {
          setKey,
          pos,
          athId,
          athName,
        }
        api.callApi(me.apiUrl, me.apiPath, 'setChange', ps).then((_res) => {
          if (_res && _res.status == 1) {
            res = _res.result
          }
          su(res)
        })
      } catch (error) {
        console.log(error)
        su(res)
      }
    })
  }
}

const api = new TApi()
const fets = new TFeTsApi()

export default fets
